﻿using Kingdee.BOS;
using Kingdee.BOS.App.Data;
using Kingdee.BOS.Core.Bill.PlugIn;
using Kingdee.BOS.Core.Bill.PlugIn.Args;
using Kingdee.BOS.Core.DynamicForm;
using Kingdee.BOS.Core.DynamicForm.PlugIn;
using Kingdee.BOS.Core.DynamicForm.PlugIn.Args;
using Kingdee.BOS.Core.FieldReader;
using Kingdee.BOS.Core.List;
using Kingdee.BOS.Core.Metadata;
using Kingdee.BOS.Core.Metadata.EntityElement;
//using static Kingdee.BOS.App.Core.Validation.EntryEntity.CompositePKValidator.KeyHelper;
using Kingdee.BOS.Core.Metadata.FieldElement;
using Kingdee.BOS.Orm;
using Kingdee.BOS.Orm.DataEntity;
using Kingdee.BOS.Resource;
using Kingdee.BOS.ServiceHelper;
using Kingdee.BOS.Util;
using Kingdee.K3.SCM.ServiceHelper;
using OfficeOpenXml.FormulaParsing.Excel.Functions.RefAndLookup;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Data;
using System.Linq;
//using static Kingdee.BOS.Cache.LRUCache<ItemType>;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
//using static Kingdee.BOS.Core.DynamicForm.PlugIn.Args.AfterShowFlexFormEventArgs;

namespace DzInfo.FormPlugIn.ZhuMuNiao
{
    [Description("zmn销售订单编辑表单插件"), HotUpdate]
    public class zmnSal : AbstractBillPlugIn
    {
        public override void BeforeSave(BeforeSaveEventArgs e)
        {
            var obj = this.Model.DataObject;
            base.BeforeSave(e);
            //this.View.Model.SetValue("F_POSW_Amount_0jm", kysgje, e.Row);//使用收款金额
            //this.View.Model.SetValue("F_zmn_kyskje", kysgje, e.Row);//可用收款金额
            DynamicObjectCollection rows = obj["POSW_Cust_Entry100001"] as DynamicObjectCollection;
            decimal ysyje = rows.Select(s => Convert.ToDecimal(s["F_POSW_Amount_0jm"])).Sum(m => m);
            this.Model.SetValue("F_zmn_ysyskjehj", ysyje, 0);
            this.Model.SetValue("F_POSW_KYQTY2", ysyje, 0);
            int i = 1;
            foreach (var row in rows)
            {
                decimal F_POSW_Amount_0jm = Convert.ToDecimal(row["F_POSW_Amount_0jm"]);
                decimal F_zmn_kyskje = Convert.ToDecimal(row["F_zmn_kyskje"]);
                if (F_POSW_Amount_0jm > F_zmn_kyskje)
                {
                    e.Cancel = true;
                    this.View.ShowErrMessage($"第{i}行，使用收款金额:{F_POSW_Amount_0jm},比可用收款金额:{F_zmn_kyskje}大，不允许保存！");
                    return;
                }
                i++;
            }
            DynamicObject cust = obj["CustId"] as DynamicObject;

            bool isJmb = GetJmb(obj, cust);
            string date = Convert.ToDateTime(obj["Date"]).ToString("yyyy-MM-dd");
            int custId = cust == null ? 0 : Convert.ToInt32(cust["id"]);
            var FPRICELISTID = cust["PRICELISTID"] as DynamicObject;
            string priListNumber = FPRICELISTID["number"].ToString();
            DynamicObjectCollection salrows = obj["SaleOrderEntry"] as DynamicObjectCollection;
            for (int j = 0; j < salrows.Count; j++)
            {
                DynamicObject mat = salrows[j]["MaterialId"] as DynamicObject;
                int matId = mat == null ? 0 : Convert.ToInt32(mat["id"]);
                decimal jmbPrice = GetJmbPrice(matId, priListNumber, date);
                this.Model.SetValue("F_zmn_jmbdj", jmbPrice, j);
            }

            DynamicObject custJDZC = cust == null ? null : cust["F_zmn_jdfkzc"] as DynamicObject;
            string jdzcNumber = custJDZC == null ? "" : Convert.ToString(custJDZC["number"]);
            decimal sd = Convert.ToDecimal(obj["F_zmn_sdje"]);
            decimal ys = GetSk(obj);
            decimal xs = GetXS(obj);
            if (!isJmb)//价目表不致，需要财务审核
            {
                this.Model.SetValue("FIsWorlk", 2);
            }
            else
            {
                switch (jdzcNumber)
                {
                    //水单30% 2025-07-29 按苏工要求改成水单+到款大于等于30%就通过，不需要财务审核
                    case "ZMNJDFKZC01":
                        if (sd + ys >= xs * 30 / 100)
                        {
                            this.Model.SetValue("FIsWorlk", 1);
                        }
                        else
                        {
                            this.Model.SetValue("FIsWorlk", 2);
                        }
                        break;
                    //全款接单
                    case "ZMNJDFKZC02":
                        if (ys >= xs)
                        {
                            this.Model.SetValue("FIsWorlk", 1);
                        }
                        else
                        {
                            this.Model.SetValue("FIsWorlk", 2);
                        }
                        break;
                    //无款接单
                    case "ZMNJDFKZC03":
                        this.Model.SetValue("FIsWorlk", 1);
                        break;
                    //50%到款后接单
                    case "ZMNJDFKZC04":
                        if (ys >= xs * 50 / 100)
                        {
                            this.Model.SetValue("FIsWorlk", 1);
                        }
                        else
                        {
                            this.Model.SetValue("FIsWorlk", 2);
                        }
                        break;
                    //到款(水单)100%接单
                    case "ZMNJDFKZC05":
                        if (ys >= xs)
                        {
                            this.Model.SetValue("FIsWorlk", 1);
                        }
                        else
                        {
                            if (sd >= xs)
                            {
                                this.Model.SetValue("FIsWorlk", 1);
                            }
                            else
                            {
                                if (ys + sd >= xs)
                                {
                                    this.Model.SetValue("FIsWorlk", 1);
                                }
                                else
                                {
                                    this.Model.SetValue("FIsWorlk", 2);
                                }
                            }
                        }
                        break;
                }
            }
        }

        private decimal GetXS(DynamicObject obj)
        {
            decimal xs = 0;
            DynamicObjectCollection fine = obj["SaleOrderFinance"] as DynamicObjectCollection;
            xs = Convert.ToDecimal(fine[0]["BillAllAmount"]);
            return xs;
        }

        private decimal GetSk(DynamicObject obj)
        {
            decimal ys = 0;
            DynamicObjectCollection ysRow = obj["POSW_Cust_Entry100001"] as DynamicObjectCollection;
            ys = ysRow.Select(s => s["F_POSW_Amount_0jm"]).Sum(p => Convert.ToDecimal(p));
            return ys;
        }

        private bool GetJmb(DynamicObject obj, DynamicObject cust)
        {
            string date = Convert.ToDateTime(obj["Date"]).ToString("yyyy-MM-dd");
            int custId = cust == null ? 0 : Convert.ToInt32(cust["id"]);
            var FPRICELISTID = cust["PRICELISTID"] as DynamicObject;
            string priListNumber = FPRICELISTID["number"].ToString();
            DynamicObjectCollection rows = obj["SaleOrderEntry"] as DynamicObjectCollection;
            foreach (var row in rows)
            {
                var rowtype = row["RowType"].ToString();
                //int RowType = row["RowType"] == null ? 0 : Convert.ToInt32(row["RowType"]);
                if (rowtype != "Son")
                {
                    DynamicObject mat = row["MaterialId"] as DynamicObject;
                    int matId = mat == null ? 0 : Convert.ToInt32(mat["id"]);
                    decimal jmbPrice = GetJmbPrice(matId, priListNumber, date);
                    decimal taxPrice = Convert.ToDecimal(row["TaxPrice"]);
                    if (jmbPrice <= 0)
                    {
                        return false;
                    }
                    if (taxPrice < jmbPrice)
                    {
                        return false;
                    }
                }
            }
            return true;
        }

        private decimal GetJmbPrice(int matId, string priListNumber, string date)
        {
            decimal jm = 0;
            string sql = string.Format(@"/*dialect*/ 
            SELECT T2.FPRICE
            FROM T_SAL_PRICELIST T0
            JOIN T_SAL_PRICELISTENTRY T2 ON T2.FID=T0.FID
            WHERE T2.FMATERIALID={0} AND T0.FNUMBER='{1}' AND T2.FEFFECTIVEDATE<='{2}' AND T2.FEXPRIYDATE>='{3}'
            AND T0.FDOCUMENTSTATUS='C' AND T0.FFORBIDSTATUS='A' AND t2.FFORBIDSTATUS='A' AND t2.FROWAUDITSTATUS='A'
            ORDER BY T0.FEFFECTIVEDATE DESC ", matId, priListNumber, date, date);
            DynamicObjectCollection doc = DBUtils.ExecuteDynamicObject(this.Context, sql);
            if (doc.Count > 0)
            {
                jm = Convert.ToDecimal(doc[0][0]);
            }
            return jm;
        }

        public override void DataChanged(DataChangedEventArgs e)
        {
            base.DataChanged(e);
            if (e.Field.Key.Equals("F_POSW_Text_jtv"))
            {
                decimal kysgje = GetKysgje((string)e.NewValue);
                this.View.Model.SetValue("F_zmn_kyskje", kysgje, e.Row);//可用收款金额
                this.View.Model.SetValue("F_POSW_Amount_0jm", kysgje, e.Row);//使用收款金额
                this.View.Model.SetValue("F_zmn_syskje", 0, e.Row);//剩余收款金额
            }
            if (e.Field.Key.Equals("FBillAllAmount"))
            {
                var obj = this.Model.DataObject;
                int fid = Convert.ToInt32(obj["id"]);
                DynamicObject customer = this.Model.DataObject["CustId"] as DynamicObject;
                decimal allAmount = (decimal)e.NewValue;
                decimal mzsdje = GetMzsdje(allAmount, customer);
                DynamicObjectCollection rows = obj["POSW_Cust_Entry100001"] as DynamicObjectCollection;
                for (int i = 0; i < rows.Count; i++)
                {
                    this.Model.SetValue("F_POSW_Amount_yaa", e.NewValue, i);
                    this.Model.SetValue("F_zmn_mzsdje", e.NewValue, i);
                }
            }
        }

        private decimal GetKysgje(string newValue)
        {
            string sql = string.Format(@"/*dialect*/ 
            select F_zmn_Ssyskje from T_AR_RECEIVEBILL where FBILLNO='{0}' ", newValue);
            DynamicObjectCollection doc = DBUtils.ExecuteDynamicObject(this.Context, sql);
            if (doc.Count > 0)
            {
                return Convert.ToDecimal(doc[0][0]);
            }
            return 0;
        }

        public override void BeforeF7Select(BeforeF7SelectEventArgs e)
        {
            base.BeforeF7Select(e);
            switch (e.FieldKey.ToUpperInvariant())
            {
                case "F_POSW_TEXT_JTV":
                    //ShowAdvanceList(e.Row);
                    ShowAR_RECEIVEBILL(e.Row);
                    break;
            }
            //if (!CanF7Select(e.FieldKey, e.Row))
            //{
            //    e.Cancel = true;
            //    return;
            //}
        }

        private void ShowAR_RECEIVEBILL(int row)
        {//AR_RECEIVEBILL
            //ListShowParameter list = new ListShowParameter();
            DynamicObject customer = this.Model.DataObject["CustId"] as DynamicObject;
            int customerId = customer == null ? 0 : Convert.ToInt32(customer["id"]);
            DynamicObjectCollection finec = this.Model.DataObject["SaleOrderFinance"] as DynamicObjectCollection;
            DynamicObject curr = finec[0]["SettleCurrId"] as DynamicObject;
            int currId = curr == null ? 0 : Convert.ToInt32(curr["id"]);
            decimal allAmount = Convert.ToDecimal(finec[0]["BillAllAmount"]);
            decimal mzsdje = GetMzsdje(allAmount, customer);
            DynamicObjectCollection skmx = this.Model.DataObject["POSW_Cust_Entry100001"] as DynamicObjectCollection;
            // 方法2：增强版（推荐 - 同时处理 null 和 DBNull）
            var ysk = skmx.Select(s => s["F_POSW_Text_jtv"])
                          .Where(value =>
                              value != null &&
                              value != DBNull.Value
                          );
            List<string> newList = new List<string>();
            foreach (var a in ysk)
            {
                string b = " and FBILLNO not in " + $"('{a}')";
                newList.Add(b);
            }
            string yskNos = string.Join("  ", newList);
            ListSelBillShowParameter list = new ListSelBillShowParameter();
            list.ListFilterParameter.Filter = string.Format("  FPAYUNITTYPE='BD_Customer' AND FPAYUNIT = '{0}' AND FCURRENCYID='{1}' AND F_ZMN_SSYSKJE>0  {2} ", customerId, currId, yskNos);
            list.FormId = "AR_RECEIVEBILL";
            list.MultiSelect = false;
            this.View.ShowForm(list, delegate (FormResult result)
            {
                ListSelectedRowCollection results = result.ReturnData as ListSelectedRowCollection;
                Dictionary<string, decimal> dic = new Dictionary<string, decimal>();
                //List<decimal> kysgjes = new List<decimal>();
                if (null != results && results.Count > 0)
                {
                    foreach (ListSelectedRow item in results)
                    {
                        string BillNo = item.BillNo;
                        DynamicObjectDataRow datarows = item.DataRow as DynamicObjectDataRow;
                        decimal amo = Convert.ToDecimal(datarows["FRECEIVEAMOUNTFOR_H"]);
                        //kysgjes.Add(Convert.ToDecimal(datarows["F_zmn_Ssyskje"]));
                        int fid = Convert.ToInt32(datarows["fid"]);
                        decimal yglje = GetYglje(fid);
                        dic.Add(BillNo, amo - yglje);
                    }
                }
                string sBillno = string.Join(",", dic.Select(s => s.Key).ToList());
                Entity entity = this.Model.BillBusinessInfo.GetEntity("F_POSW_Entity_k5h");
                var rowEntry = this.Model.GetEntityDataObject(entity, row);
                var yNo = rowEntry["F_POSW_Text_jtv"];
                if (yNo.IsNullOrEmptyOrWhiteSpace())
                {
                    this.View.Model.SetValue("F_POSW_Text_jtv", sBillno, row);
                    decimal kglje = dic.Select(s => s.Value).Sum(p => Convert.ToDecimal(p));

                    this.View.Model.SetValue("F_POSW_Amount_yaa", allAmount, row);//本单关联金额

                    this.View.Model.SetValue("F_zmn_mzsdje", mzsdje, row);//满足审单金额
                }

            });
        }

        private decimal GetMzsdje(decimal allAmount, DynamicObject cust)
        {
            decimal mzsdje = 0;
            DynamicObject custJDZC = cust == null ? null : cust["F_zmn_jdfkzc"] as DynamicObject;
            string jdzcNumber = custJDZC == null ? "" : Convert.ToString(custJDZC["number"]);
            switch (jdzcNumber)
            {
                case "ZMNJDFKZC01":
                    mzsdje = allAmount * 0.3m;
                    break;
                case "ZMNJDFKZC02":
                    mzsdje = allAmount;
                    break;
                case "ZMNJDFKZC03":
                    mzsdje = 0;
                    break;
                case "ZMNJDFKZC04":
                    mzsdje = allAmount * 0.5m;
                    break;
                case "ZMNJDFKZC05":
                    mzsdje = allAmount;
                    break;
            }
            return mzsdje;
        }

        private decimal GetYglje(int fid)
        {
            string sql = string.Format(@"/*dialect*/ 
            SELECT F_POSW_AMOUNT_ZCM FROM T_AR_RECEIVEBILL WHERE FID={0} ", fid);
            DynamicObjectCollection doc = DBUtils.ExecuteDynamicObject(this.Context, sql);
            if (doc.Count > 0)
            {
                return Convert.ToDecimal(doc[0][0]);
            }
            return 0;
        }

        private void ShowAdvanceList(int row)
        {
            //    EntryEntity entryEntity = ((IDynamicFormModel)((AbstractBillPlugIn)this).View.Model).BusinessInfo.GetEntryEntity("FSaleOrderPlan");
            //    DynamicObject dyRecPlanRow = ((IDynamicFormModel)((AbstractBillPlugIn)this).View.Model).GetEntityDataObject((Entity)(object)entryEntity, row);
            //    DynamicObjectCollection val = null;
            //    if (dyRecPlanRow.DynamicObjectType.Properties.Contains("POSW_Cust_Entry100001"))
            //    {
            //        object obj = dyRecPlanRow["POSW_Cust_Entry100001"];
            //        val = (DynamicObjectCollection)((obj is DynamicObjectCollection) ? obj : null);
            //    }
            //    object value = ((IDynamicFormModel)((AbstractBillPlugIn)this).View.Model).GetValue("FSaleOrgId");
            //    DynamicObject val2 = (DynamicObject)((value is DynamicObject) ? value : null);
            //    object value2 = ((IDynamicFormModel)((AbstractBillPlugIn)this).View.Model).GetValue("FSettleId");
            //    DynamicObject val3 = (DynamicObject)((value2 is DynamicObject) ? value2 : null);
            //    object value3 = ((IDynamicFormModel)((AbstractBillPlugIn)this).View.Model).GetValue("FSettleCurrId");
            //    DynamicObject val4 = (DynamicObject)((value3 is DynamicObject) ? value3 : null);
            //    object value4 = ((IDynamicFormModel)((AbstractBillPlugIn)this).View.Model).GetValue("FCustId");
            //    DynamicObject val5 = (DynamicObject)((value4 is DynamicObject) ? value4 : null);
            //    long num = ((val2 == null) ? 0 : Convert.ToInt64(val2["Id"]));
            //    long num2 = ((val3 == null) ? 0 : Convert.ToInt64(val3["Id"]));
            //    long num3 = ((num2 != 0) ? num2 : ((val5 == null) ? 0 : Convert.ToInt64(val5["Id"])));
            //    long num4 = ((val4 == null) ? 0 : Convert.ToInt64(val4["Id"]));
            //    object obj2 = ((AbstractDynamicFormPlugIn)this).Model.DataObject["SaleOrderEntry"];
            //    DynamicObjectCollection val6 = (DynamicObjectCollection)((obj2 is DynamicObjectCollection) ? obj2 : null);
            //    int entryRowCount = ((IDynamicFormModel)((AbstractBillPlugIn)this).View.Model).GetEntryRowCount("FSaleOrderEntry");
            //    string text = "";
            //    List<long> list = new List<long>();
            //    for (int i = 0; i < entryRowCount; i++)
            //    {
            //        DynamicObject val7 = ((Collection<DynamicObject>)(object)val6)[i];
            //        if (!list.Contains(Convert.ToInt64(val7["SettleOrgId_Id"])))
            //        {
            //            list.Add(Convert.ToInt64(val7["SettleOrgId_Id"]));
            //            text = text + Convert.ToString(val7["SettleOrgId_Id"]) + ",";
            //        }
            //    }
            //    if (text.Count() > 0)
            //    {
            //        text = text.Substring(0, text.Count() - 1);
            //    }
            //    if (string.IsNullOrWhiteSpace(text))
            //    {
            //        text = "0";
            //    }
            //    long num5 = Convert.ToInt64(((AbstractBillPlugIn)this).View.Model.GetPKValue());
            //    if (((AbstractElement)((IDynamicFormModel)((AbstractBillPlugIn)this).View.Model).BusinessInfo.GetForm()).Id.Equals("SAL_XORDER"))
            //    {
            //        num5 = Convert.ToInt64(((IDynamicFormModel)((AbstractBillPlugIn)this).View.Model).GetValue("FPKIDX_H"));
            //    }
            //((IDynamicFormModel)((AbstractBillPlugIn)this).View.Model).GetValue("FRecConditionId");
            //    DynamicObjectCollection val8 = null;
            //    val8 = SaleServiceHelper2.GetReceBillListNew(((IDynamicFormView)((AbstractBillPlugIn)this).View).Context, num3, num4, num, text, num5, (List<long>)null);
            //    List<string> list2 = new List<string>();
            //    if (dyRecPlanRow != null && !ObjectUtils.IsNullOrEmptyOrWhiteSpace(dyRecPlanRow["RelBillNo"]))
            //    {
            //        string[] source = Convert.ToString(dyRecPlanRow["RelBillNo"]).Split(',');
            //        list2 = source.ToList();
            //    }
            //    List<long> list3 = new List<long>();
            //    if (val != null && ((Collection<DynamicObject>)(object)val).Count > 0)
            //    {
            //        foreach (DynamicObject item in (Collection<DynamicObject>)(object)val)
            //        {
            //            if (item != null && item.DynamicObjectType.Properties.Contains("ADVANCEENTRYID"))
            //            {
            //                long num6 = Convert.ToInt64(item["ADVANCEENTRYID"]);
            //                if (num6 > 0 && !list3.Contains(num6))
            //                {
            //                    list3.Add(num6);
            //                }
            //            }
            //        }
            //    }
            DynamicFormShowParameter val9 = new DynamicFormShowParameter();
            val9.Height = 600;
            val9.Width = 1024;
            val9.FormId = "Sal_ReceiveList";//34945c48-b58c-4ade-9a74-d3a200fd6a3b
            //val9.FormId = "AR_RECEIVEBILL";//34945c48-b58c-4ade-9a74-d3a200fd6a3b
            val9.SyncCallBackAction = true;
            val9.ParentPageId = ((IDynamicFormView)((AbstractBillPlugIn)this).View).PageId;
            val9.PageId = SequentialGuid.NewGuid().ToString();
            string key = "SessionReceiveKey";
            string text2 = "SessionReceiveValue";
            val9.CustomParams.Add("RowIndex", Convert.ToString(row));
            val9.CustomParams.Add(key, text2);
            string value5 = Convert.ToString(((IDynamicFormModel)((AbstractBillPlugIn)this).View.Model).GetValue("FDocumentStatus"));
            val9.CustomParams.Add("orderDocumentStatus", value5);

            val9.CustomComplexParams.Add("ListRelBillEntryIds", "100001");
            //if (val4 != null)
            //{
            //    val9.CustomParams.Add("AmountDigits", val4["AmountDigits"].ToString());
            //}
            //if (list2.Count > 0)
            //{
            //    val9.CustomComplexParams.Add("ListRelBillNos", list2);
            //}
            //if (list3.Count > 0)
            //{
            //    val9.CustomComplexParams.Add("ListRelBillEntryIds", list3);
            //}
            //((IDynamicFormView)((AbstractBillPlugIn)this).View).Session[text2] = val8;
            ((IDynamicFormView)((AbstractBillPlugIn)this).View).ShowForm(val9, (Action<FormResult>)delegate (FormResult result)
            {
                //IL_000e: Unknown result type (might be due to invalid IL or missing references)
                //IL_0014: Expected O, but got Unknown
                if (result.ReturnData != null)
                {
                    DynamicObjectCollection val10 = (DynamicObjectCollection)result.ReturnData;
                    //decimal num7 = Convert.ToDecimal(dyRecPlanRow["RecAdvanceAmount"]);
                    //if (!(num7 == 0m) && val10 != null && ((Collection<DynamicObject>)(object)val10).Count >= 1)
                    //{
                    //    DealData(val10, dyRecPlanRow, row);
                    //}
                }
            });
        }

        private void DealData(DynamicObjectCollection dynamicObjs, DynamicObject dyRecPlanRow, int row)
        {

            decimal num = Convert.ToDecimal(dyRecPlanRow["RecAdvanceAmount"]);
            decimal num2 = 0m;
            List<string> list = new List<string>();
            bool flag = false;
            int num3 = 1;
            Entity entity = ((IDynamicFormView)((AbstractBillPlugIn)this).View).BusinessInfo.GetEntity("FSaleOrderPlanEntry");
            DynamicObjectCollection entityDataObject = ((IDynamicFormModel)((AbstractBillPlugIn)this).View.Model).GetEntityDataObject(entity);
            Field field = ((IDynamicFormModel)((AbstractBillPlugIn)this).View.Model).BusinessInfo.GetField("FPESettleOrgId");
            BaseDataField val = (BaseDataField)(object)((field is BaseDataField) ? field : null);
            List<DynamicObject> list2 = (from p in (IEnumerable<DynamicObject>)dynamicObjs
                                         orderby Convert.ToDecimal(p["PREMATCHAMOUNTFOR_SO"]) descending, Convert.ToInt64(p["ENTRYID"])
                                         select p).ToList();
            Dictionary<string, decimal> dictionary = new Dictionary<string, decimal>();
            foreach (DynamicObject item2 in list2)
            {
                string key = Convert.ToString(item2["BILLNO"]);
                decimal num4 = Convert.ToDecimal(item2["ASSTOTALAMOUNTFOR"]);
                if (!dictionary.ContainsKey(key))
                {
                    dictionary.Add(key, num4);
                }
                else
                {
                    dictionary[key] += num4;
                }
            }
            Dictionary<string, decimal> dictionary2 = new Dictionary<string, decimal>();
            DynamicObject dataObject = ((IDynamicFormModel)((AbstractBillPlugIn)this).View.Model).DataObject;
            List<DynamicObject> list3 = new List<DynamicObject>();
            List<DynamicObject> list4 = new List<DynamicObject>();
            new Dictionary<long, long>();
            if (dataObject != null)
            {
                object obj = dataObject["SaleOrderPlan"];
                DynamicObjectCollection val2 = (DynamicObjectCollection)((obj is DynamicObjectCollection) ? obj : null);
                if (val2 != null && ((Collection<DynamicObject>)(object)val2).Count > 0)
                {
                    int num5 = 0;
                    foreach (DynamicObject item3 in (Collection<DynamicObject>)(object)val2)
                    {
                        if (num5 == row)
                        {
                            num5++;
                            object obj2 = item3["SAL_ORDERPLANENTRY"];
                            DynamicObjectCollection val3 = (DynamicObjectCollection)((obj2 is DynamicObjectCollection) ? obj2 : null);
                            if (val3 == null || ((Collection<DynamicObject>)(object)val3).Count <= 0)
                            {
                                continue;
                            }
                            foreach (DynamicObject item4 in (Collection<DynamicObject>)(object)val3)
                            {
                                decimal num6 = Convert.ToDecimal(item4["ActRecAmount"]);
                                if (num6 < 0m)
                                {
                                    list3.Add(item4);
                                }
                                else
                                {
                                    list4.Add(item4);
                                }
                            }
                            continue;
                        }
                        num5++;
                        object obj3 = item3["SAL_ORDERPLANENTRY"];
                        DynamicObjectCollection val4 = (DynamicObjectCollection)((obj3 is DynamicObjectCollection) ? obj3 : null);
                        if (val4 == null || ((Collection<DynamicObject>)(object)val4).Count <= 0)
                        {
                            continue;
                        }
                        foreach (DynamicObject item5 in (Collection<DynamicObject>)(object)val4)
                        {
                            string key2 = Convert.ToString(item5["AdvanceNo"]);
                            decimal num7 = Convert.ToDecimal(item5["ActRecAmount"]);
                            if (!dictionary2.ContainsKey(key2))
                            {
                                dictionary2.Add(key2, num7);
                            }
                            else
                            {
                                dictionary2[key2] += num7;
                            }
                        }
                    }
                }
            }
            decimal num8 = 0m;
            decimal num9 = num;
            foreach (DynamicObject item6 in list2)
            {
                num8 = Convert.ToDecimal(item6["ASSTOTALAMOUNTFOR"]);
                if (flag)
                {
                    num8 = 0m;
                }
                else if (num9 - num8 <= 0m)
                {
                    num8 = num9;
                    flag = true;
                }
                else
                {
                    num9 -= num8;
                }
                string key3 = Convert.ToString(item6["BILLNO"]);
                if (!dictionary2.ContainsKey(key3))
                {
                    dictionary2.Add(key3, num8);
                }
                else
                {
                    dictionary2[key3] += num8;
                }
            }
            bool flag2 = ((IEnumerable<DynamicObject>)entityDataObject).ToList().Exists((DynamicObject n) => Convert.ToDecimal(n["ActRecAmount"]) < 0m);
            flag = false;
            List<string> list5 = new List<string>();
            Dictionary<long, decimal> dictionary3 = new Dictionary<long, decimal>();
            if (!flag2)
            {
                ((Collection<DynamicObject>)(object)entityDataObject).Clear();
            }
            else
            {
                List<long> list6 = list3.Select((DynamicObject n) => Convert.ToInt64(n["ADVANCEENTRYID"])).Distinct().ToList();
                List<long> selectedRecEntryIds = list2.Select((DynamicObject n) => Convert.ToInt64(n["EntryId"])).ToList();
                Dictionary<long, long> dictionary4 = new Dictionary<long, long>();
                List<long> list7 = (from n in list4
                                    where selectedRecEntryIds.Contains(Convert.ToInt64(n["ADVANCEENTRYID"]))
                                    select Convert.ToInt64(n["ADVANCEENTRYID"])).Distinct().ToList();
                DynamicObjectCollection recEntryIdsByReFunBillEntryIds = SaleServiceHelper2.GetRecEntryIdsByReFunBillEntryIds(((AbstractDynamicFormPlugIn)this).Context, list6, list7);
                List<long> list8 = new List<long>();
                if (recEntryIdsByReFunBillEntryIds != null)
                {
                    foreach (DynamicObject item7 in (Collection<DynamicObject>)(object)recEntryIdsByReFunBillEntryIds)
                    {
                        long num10 = Convert.ToInt64(item7["REFUNENTRYID"]);
                        list8.Add(num10);
                        if (!dictionary4.ContainsKey(num10))
                        {
                            long value = Convert.ToInt64(item7["RECENTRYID"]);
                            dictionary4.Add(num10, value);
                        }
                    }
                }
                List<int> list9 = new List<int>();
                for (int i = 0; i < ((Collection<DynamicObject>)(object)entityDataObject).Count; i++)
                {
                    decimal num11 = Convert.ToDecimal(((Collection<DynamicObject>)(object)entityDataObject)[i]["ActRecAmount"]);
                    if (num11 < 0m)
                    {
                        long num12 = Convert.ToInt64(((Collection<DynamicObject>)(object)entityDataObject)[i]["ADVANCEENTRYID"]);
                        if (list8.Contains(num12))
                        {
                            list5.Add(Convert.ToString(((Collection<DynamicObject>)(object)entityDataObject)[i]["AdvanceNo"]));
                            if (dictionary4.ContainsKey(num12))
                            {
                                if (!dictionary3.ContainsKey(dictionary4[num12]))
                                {
                                    dictionary3.Add(dictionary4[num12], 0m);
                                }
                                dictionary3[dictionary4[num12]] += num11;
                            }
                            ((Collection<DynamicObject>)(object)entityDataObject)[i]["Seq"] = num3;
                            num3++;
                            continue;
                        }
                    }
                    list9.Add(i);
                }
                if (list9.Count > 0)
                {
                    list9 = list9.OrderByDescending((int n) => n).ToList();
                    foreach (int item8 in list9)
                    {
                        ((Collection<DynamicObject>)(object)entityDataObject).RemoveAt(item8);
                    }
                }
            }
            Dictionary<string, decimal> recBillAmount = GetRecBillAmount();
            foreach (DynamicObject item9 in list2)
            {
                DynamicObject val5 = new DynamicObject(entity.DynamicObjectType);
                decimal num13 = Convert.ToDecimal(item9["ASSTOTALAMOUNTFOR"]);
                string text = Convert.ToString(item9["BILLNO"]);
                string text2 = Convert.ToString(item9["EntryId"]);
                text += text2;
                if (!ObjectUtils.IsNullOrEmptyOrWhiteSpace((object)text) && recBillAmount.ContainsKey(text))
                {
                    num13 -= recBillAmount[text];
                }
                if (flag)
                {
                    num13 = 0m;
                }
                else if (num - num13 <= 0m)
                {
                    num13 = num;
                    flag = true;
                }
                else
                {
                    num -= num13;
                }
                val5["AdvanceNo"] = item9["BILLNO"].ToString();
                val5["ADVANCEID"] = Convert.ToInt64(item9["ID"]);
                val5["AdvanceSeq"] = item9["SEQ"].ToString();
                long num14 = Convert.ToInt64(item9["ENTRYID"]);
                val5["ADVANCEENTRYID"] = num14;
                val5["ActRecAmount"] = num13;
                if (flag2 && dictionary3.ContainsKey(num14))
                {
                    val5["ActRecAmount"] = num13 + Math.Abs(dictionary3[num14]);
                }
                val5["RemainAmount"] = Convert.ToDecimal(item9["ASSTOTALAMOUNTFOR"]);
                val5["PREMATCHAMOUNTFOR"] = (item9.DynamicObjectType.Properties.Contains("PreMatchAmountFor_ENT") ? Convert.ToDecimal(item9["PreMatchAmountFor_ENT"]) : 0m);
                if (StringUtils.EqualsIgnoreCase(((AbstractElement)((IDynamicFormModel)((AbstractBillPlugIn)this).View.Model).BusinessInfo.GetForm()).Id, "SAL_XORDER"))
                {
                    val5["PKIDX"] = item9["PKIDX"];
                }
                val5["SettleOrgId_Id"] = item9["SettleOrgId_Id"];
                val5["SettleOrgId"] = BusinessDataServiceHelper.LoadSingle(((AbstractDynamicFormPlugIn)this).Context, (object)Convert.ToInt64(item9["SettleOrgId_Id"]), val.RefFormDynamicObjectType, (OperateOption)null);
                val5["Seq"] = num3++;
                num2 += num13;
                string item = item9["BILLNO"].ToString();
                if (!list.Contains(item))
                {
                    list.Add(item);
                }
                ((Collection<DynamicObject>)(object)entityDataObject).Add(val5);
            }
            dyRecPlanRow["RecAmount"] = num2;
            if (flag2 && list5.Count > 0)
            {
                list.AddRange(list5);
            }
            dyRecPlanRow["RelBillNo"] = string.Join(",", list.ToArray());
            int num15 = Convert.ToInt32(dyRecPlanRow["Seq"]);
            ((IDynamicFormModel)((AbstractBillPlugIn)this).View.Model).DataChanged = true;
            //((IDynamicFormView)((AbstractBillPlugIn)this).View).UpdateView("FRecAmount", num15 - 1);
            ((IDynamicFormView)((AbstractBillPlugIn)this).View).UpdateView("F_POSW_Text_jtv", num15 - 1);
            Field field2 = ((IDynamicFormView)((AbstractBillPlugIn)this).View).BusinessInfo.GetField("FRecAmount");
            DecimalField val6 = (DecimalField)(object)((field2 is DecimalField) ? field2 : null);
            if (!string.IsNullOrWhiteSpace(val6.SummaryLinkField))
            {
                ((IDynamicFormModel)((AbstractBillPlugIn)this).View.Model).SummaryDataAndFill(field2, val6.SummaryLinkField);
            }
            this.View.UpdateView("FSaleOrderPlan");
        }

        private Dictionary<string, decimal> GetRecBillAmount()
        {
            Dictionary<string, decimal> dictionary = new Dictionary<string, decimal>();
            object obj = ((IDynamicFormModel)((AbstractBillPlugIn)this).View.Model).DataObject["SaleOrderPlan"];
            DynamicObjectCollection val = (DynamicObjectCollection)((obj is DynamicObjectCollection) ? obj : null);
            if (val != null && ((Collection<DynamicObject>)(object)val).Count > 0)
            {
                ((DataEntityCollection<DynamicObject>)(object)val).Sort<int>((Func<DynamicObject, int>)((DynamicObject n) => Convert.ToInt32(n["Seq"])), (IComparer<int>)null);
                int num = ((IDynamicFormModel)((AbstractBillPlugIn)this).View.Model).GetEntryCurrentRowIndex("FSaleOrderPlan") + 1;
                foreach (DynamicObject item in (Collection<DynamicObject>)(object)val)
                {
                    int num2 = Convert.ToInt32(item["Seq"]);
                    if (num2 == num)
                    {
                        continue;
                    }
                    object obj2 = item["SAL_ORDERPLANENTRY"];
                    DynamicObjectCollection val2 = (DynamicObjectCollection)((obj2 is DynamicObjectCollection) ? obj2 : null);
                    if (val2 == null || ((Collection<DynamicObject>)(object)val2).Count <= 0)
                    {
                        continue;
                    }
                    foreach (DynamicObject item2 in (Collection<DynamicObject>)(object)val2)
                    {
                        string text = Convert.ToString(item2["AdvanceNo"]);
                        string text2 = Convert.ToString(item2["ADVANCEENTRYID"]);
                        text += text2;
                        decimal num3 = Convert.ToDecimal(item2["ActRecAmount"]);
                        if (!ObjectUtils.IsNullOrEmptyOrWhiteSpace((object)text))
                        {
                            if (!dictionary.ContainsKey(text))
                            {
                                dictionary[text] = num3;
                            }
                            else
                            {
                                dictionary[text] += num3;
                            }
                        }
                    }
                }
            }
            return dictionary;
        }

        private bool CanF7Select(string key, int row)
        {
            bool result = true;
            switch (key.ToUpperInvariant())
            {
                case "FRELBILLNO":
                    {
                        decimal num = Convert.ToDecimal((this.View.Model).GetValue("FRecAdvanceAmount", row));
                        if (num <= 0m)
                        {
                            ((this).View).ShowMessage(string.Format(ResManager.LoadKDString("第{0}行应收金额为零，不能关联收款单！", "004019030001066", (SubSystemType)5, new object[0]), (row + 1).ToString()), (MessageBoxType)0);
                            result = false;
                        }
                        string text2 = ((this).View.Model).GetValue("FNeedRecAdvance", row).ToString().ToUpperInvariant();
                        if (text2 == "FALSE")
                        {
                            ((this).View).ShowMessage(string.Format(ResManager.LoadKDString("第{0}行未勾选是否预收，不能关联收款单！", "004019030001063", (SubSystemType)5, new object[0]), (row + 1).ToString()), (MessageBoxType)0);
                            result = false;
                        }
                        break;
                    }
                case "FRECAMOUNT":
                    {
                        string text = Convert.ToString(((this).View.Model).GetValue("FRelBillNo", row));
                        if (ObjectUtils.IsNullOrEmptyOrWhiteSpace((object)text))
                        {
                            (this.View).ShowMessage(string.Format(ResManager.LoadKDString("第{0}行关联单号为空，请先选择预收单！", "004019030001069", (SubSystemType)5, new object[0]), (row + 1).ToString()), (MessageBoxType)0);
                            result = false;
                        }
                        break;
                    }
            }
            return result;
        }
    }
}
